<template>
  <div class="container">
    <el-header class="title">所有商品</el-header>
    <el-row class="mt-3">
      <el-col :span="6" v-for="item in items" :key="item.id">
        <el-card :body-style="{ padding: '0px' }" class="m-1">
          <img :src="item.imgUrl" class="image">
          <div style="padding: 14px;">
            <span>{{ item.name }}</span>
            <div class="bottom clearfix">
              <div class="price">{{ '￥' + item.price }}</div>
              <AddToCart />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
import AddToCart from "@/components/item/addToCart.vue";

export default {
  name: "item",
  components: {AddToCart},
  data() {
    return {
      items: [],
      defaultImg:'../../assets/items/1.png'
    };
  },

  methods: {
    fetchProducts() {
      axios.get('/item/find')
          .then(response => {
            this.items = response.data.map(item => ({
              ...item,
              imgUrl: '/assets/items/' + item.imgUrl
            }));
          })
          .catch(error => {
            console.error('There was an error fetching the items:', error);
          });
    },
    addToCart(item) {
      // 加入购物车的逻辑
      console.log('Added to cart:', item);
    }
  },
  created() {
    this.fetchProducts();
  },
  mounted() {
    this.fetchProducts();
  },
  watch:{
    // 监听路由变化
    '$route': function(newRoute, oldRoute) {
      // 检查路由是否真的发生了变化（路径或参数）
      if (newRoute.path !== oldRoute.path) {
        // 调用方法来更新数据
        this.fetchProducts();
      }
    }
  }
}
</script>

<style scoped>
.container {
  text-align: center; /* 设置文本居中 */
}

.title {
  margin-top: 20px;
  width: 25%;
  border: 1px solid black;
  padding: 10px 0;
  font-size: 20px;
  margin-left: auto; /* 添加自动外边距实现水平居中 */
  margin-right: auto; /* 添加自动外边距实现水平居中 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.el-card {
  margin-bottom: 20px; /* 添加卡片底部间距 */
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1); /* 添加卡片阴影 */
}
.el-col{
  height: 300px;
//border: 1px solid red;
}
.image {
  width: 100%; /* 使图片宽度充满卡片 */
  display: block; /* 防止图片下方出现间隙 */
}


.bottom {
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: space-between; /* 两端分布 */
  align-items: center; /* 垂直居中 */
  margin-top: 13px; /* 添加价格和按钮的顶部间距 */
}

.price {
  font-size: 20px; /* 调整价格字体大小 */
  color: #999; /* 调整价格颜色 */
}

.button {
  padding: 0; /* 移除按钮的内边距 */
  float: right; /* 将按钮右浮动 */
}

.clearfix:before,
.clearfix:after {
  display: table; /* 清除浮动 */
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
